// const BASE_URL = 'http://192.168.123.45:18080'; //宿舍网关地址
const BASE_URL = 'http://localhost:18080'; //网关地址
// const BASE_URL = 'http://192.168.64.232:18080'; //手机局域网网关地址

const request = {
  // 基础请求方法
  async request(method, url, data) {
    return new Promise((resolve, reject) => {
      const accessTokenBCrypt = wx.getStorageSync('accessTokenBCrypt');
      const refreshTokenBCrypt = wx.getStorageSync('refreshTokenBCrypt');
      
      wx.request({
        url: `${BASE_URL}${url}`,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': accessTokenBCrypt ? accessTokenBCrypt : '',
          'refreshTokenBCrypt': refreshTokenBCrypt ? refreshTokenBCrypt : ''
        },
        success(res) {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else if (res.statusCode === 401) {
            wx.removeStorageSync('accessTokenBCrypt');
            wx.removeStorageSync('refreshTokenBCrypt');
            wx.removeStorageSync('userInfo');
            reject(new Error('登录已过期'));
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        },
        fail(err) {
          console.error('请求失败:', err);
          reject(new Error('网络请求失败'));
        }
      });
    });
  },

  // GET请求
  get(url, params) {
    return this.request('GET', url, params);
  },

  // POST请求
  post(url, data) {
    return this.request('POST', url, data);
  },
  //PUT请求
  put(url, params) {
    return this.request('PUT', url, params);
  },
  //DELETE请求
  delete(url, params) {
    return this.request('DELETE', url, params);
  }
};

export default request;